	package com.thti.mecool.client.activity;

import java.util.List;

import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.threeti.mecool.mobile.interfaces.dto.ProjectStoreDto;
import com.threeti.mecool.mobile.interfaces.dto.ProjectWithOnlyStoresDto;
import com.thti.mecool.client.base.BaseActivity;
import com.thti.mecool.client.base.Cache;
import com.thti.mecool.client.command.send.communication.CommunicationSend;
import com.thti.mecool.client.command.send.system.GetSend;
import com.thti.mecool.client.model.biz.CommunicationBizImpl;
import com.thti.mecool.client.model.po.Communication;
import com.thti.mecool.client.protocol.MessageInfo;
import com.thti.mecool.client.protocol.communication.AddCommunicationProtocol;
import com.thti.mecool.client.protocol.system.ProjectResultProtocol;
import com.thti.mecool.client.util.RegexPattern;
import com.thti.mecool.client.util.StringUtil;
import com.thti.mecool.client.util.Util;
import com.thti.mecool.client.widget.AlterDialogWidget;
import com.thti.mecool.client.widget.ProgressDialogWidget;
import com.thti.mecool.client.widget.Toolbar;

public class AddCommicationRecordActivity extends BaseActivity {
	private EditText title,name,occupation,tel,content;
	private LinearLayout selectProject,selectShop,selectTel;
	private TextView showProject,showShop,showTel;
	String[] projects,shops;
	private Button save,cancel;
	private ProgressDialogWidget progressDialogWidget;
	Context mContext;
	AddCommunicationProtocol addCommunicationToServer;
	Communication addCommunicationToDb;
	CommunicationBizImpl communicationDbOperation;
	ProjectResultProtocol projectResultProtocol;
	public static Handler handler;
	MessageInfo messageInfo;
	List<ProjectWithOnlyStoresDto> list;
	List<ProjectStoreDto> projStoresDtos;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		this.noTitle();
		setContentView(R.layout.mecool_add_com_record);
		Cache.add(this);
		//关闭输入法
		this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
		mContext=this;
		init();
		getOnclick();
		initToolbar();
		progressDialogWidget = new ProgressDialogWidget(this);
		progressDialogWidget.setDismissTime(16);
		handler=new Handler(){
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				Bundle bundle=msg.getData();
				if(msg.what==0xAB){
					messageInfo=(MessageInfo) bundle.getSerializable("commessage");
					isAddServerSuccess(messageInfo);
				}else if(msg.what==0xBB){	
					projectResultProtocol=(ProjectResultProtocol) bundle.getSerializable("projectresult");
					progressDialogWidget.dismiss();
					isSearchProject(projectResultProtocol);
				}else if(msg.what==0xBC){
					messageInfo=(MessageInfo)bundle.getSerializable("msginfo");
					progressDialogWidget.dismiss();
					showProjectAndStoreFromServer(messageInfo);
				}
				
			}
			
		};
		GetSend.getProject(BaseActivity.getCurrentUser().getLoginName());
	}
	
	private void getOnclick(){
		selectProject.setOnClickListener(new ClickEvent());
		selectShop.setOnClickListener(new ClickEvent());		
		selectTel.setOnClickListener(new ClickEvent());		
		save.setOnClickListener(new ClickEvent());		
		cancel.setOnClickListener(new ClickEvent());
	}
	
	private void init(){
		title=(EditText)findViewById(R.id.mecool_add_com_record_title);
		StringUtil.lengthFilter(this, title, 50,"最多只能输入50位");
		name=(EditText)findViewById(R.id.mecool_add_com_record_name);
		StringUtil.lengthFilter(this, name, 20,"最多只能输入20位");
		occupation=(EditText)findViewById(R.id.mecool_add_com_record_position);
		StringUtil.lengthFilter(this, occupation, 20,"最多只能输入20位");
		tel=(EditText)findViewById(R.id.mecool_add_com_record_tel);
		StringUtil.lengthFilter(this, tel, 20,"最多只能输入20位");
		content=(EditText)findViewById(R.id.mecool_add_com_record_content);
		StringUtil.lengthFilter(this, content, 150,"最多只能输入150位");
		selectProject=(LinearLayout)findViewById(R.id.mecool_add_com_record_select_project);
		showProject=(TextView)findViewById(R.id.mecool_add_com_record_show_project);
		selectShop=(LinearLayout)findViewById(R.id.mecool_add_com_record_select_shop);
		showShop=(TextView)findViewById(R.id.mecool_add_com_record_show_shop);
		selectTel=(LinearLayout)findViewById(R.id.mecool_add_com_record_select_tel);
		showTel=(TextView)findViewById(R.id.mecool_add_com_record_show_tel);
		save=(Button)findViewById(R.id.mecool_add_com_record_save);
		cancel=(Button)findViewById(R.id.mecool_add_com_record_cancel);
		addCommunicationToServer=new AddCommunicationProtocol();
		addCommunicationToDb=new Communication();
		communicationDbOperation=new CommunicationBizImpl(mContext);
	}
	
	class ClickEvent implements OnClickListener{

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.mecool_add_com_record_select_project:
				if(projects!=null){
					AlterDialogWidget shopDialog=new AlterDialogWidget(AddCommicationRecordActivity.this);
					shopDialog.setTitle("选择所在项目");
					shopDialog.setItems(projects);
					shopDialog.setReturnView(showProject);
					showShop.setText("");
					shopDialog.show();
				}else{
					Util.sendToast(mContext, "无数据");
				}
				break;
			case R.id.mecool_add_com_record_select_shop:
				if(projects!=null){
					if(isProjectSelected()){
						showShops(showProject.getText().toString());
						if(shops!=null&&shops.length!=0){
							AlterDialogWidget ProjectDialog=new AlterDialogWidget(AddCommicationRecordActivity.this);
							ProjectDialog.setTitle("选择相关终端");
							ProjectDialog.setItems(shops);
							ProjectDialog.setReturnView(showShop);
							ProjectDialog.show();
						}else{
							Util.sendToast(mContext, "无门店");
						}
					}else{
						Util.sendToast(mContext,"请先选择项目");
					}
				}else{
					Util.sendToast(mContext, "无数据");
				}
				break;
			case R.id.mecool_add_com_record_select_tel:
				AlterDialogWidget telDialog=new AlterDialogWidget(AddCommicationRecordActivity.this);
				telDialog.setTitle("选择沟通方式");
				telDialog.setItems(new String[]{"邮件","电话","短信","网络聊天"});
				telDialog.setReturnView(showTel);
				telDialog.show();
				break;
			case R.id.mecool_add_com_record_save:
				addComRecord();
				break;
			case R.id.mecool_add_com_record_cancel:
				Builder builder = new Builder(AddCommicationRecordActivity.this);
				builder.setMessage("您确定要退出吗?");
				builder.setPositiveButton("确定", dialogOnClickListener)
						.setNegativeButton("取消", dialogOnClickListener);
				builder.create();
				builder.show();	
				break;
			}
		}
		
	}
	
	private DialogInterface.OnClickListener dialogOnClickListener = new DialogInterface.OnClickListener() {
		@Override
		public void onClick(DialogInterface dialog, int which) {
			switch (which) {
			case -1:
				dialog.dismiss();
				finish();
				break;
			default:
				dialog.dismiss();
			}
		}
	};
	
	public void initToolbar(){
		Toolbar toolbar=new Toolbar(this);
		Toolbar.hideRightButton();
		toolbar.setToolbarCentreText("添加沟通记录");
		Toolbar.left_btn.setOnClickListener(leftbuttonListener);
		Toolbar.left_btn.setImageResource(R.drawable.mecool_go_back);
	}
	private OnClickListener leftbuttonListener=new ImageButton.OnClickListener(){

		@Override
		public void onClick(View v) {
			finish();
		}};
	
	private void isSearchProject(ProjectResultProtocol projectresultprotocol){
		if(projectresultprotocol.getStatus()==1){		
			list=projectresultprotocol.getProjwithstores();
			projects=new String[list.size()];
			for(int i=0;i<list.size();i++){
				projects[i]=list.get(i).getName();
			}		
		}
	}	
	
	
	
	private boolean isProjectSelected(){
		boolean isSelected=false;
		for(int i=0;i<projects.length;i++){
			if(showProject.getText().toString().equals(projects[i])){
				isSelected=true;
			}
		}
		return isSelected;
	}
	
	private void showShops(String whitchProject){
		list=projectResultProtocol.getProjwithstores();
		for(int i=0;i<list.size();i++){
			if(projectResultProtocol.getProjwithstores().get(i).getName().equals(whitchProject)){
				projStoresDtos=projectResultProtocol.getProjwithstores().get(i).getProjStores();
//				shops=new String[projStoresDtos.size()+1];
//				shops[0]="无门店";
				shops=new String[projStoresDtos.size()];
//				for(int j=1;j<shops.length;j++){
//					shops[j]=projStoresDtos.get(j-1).getName();
//				}
				for(int j=0;j<shops.length;j++){
				shops[j]=projStoresDtos.get(j).getName();
			}
			}
		}
		
	}
	
	private String findSelectedProjectId(String name){
		String id=null;
		for(int i=0;i<list.size();i++){
			if(list.get(i).getName().equals(name)){
				id=list.get(i).getId();
			}
		}
		return id;
	}
	
	private String findSelectedShopId(String name){
		String id=null;
		for(int i=0;i<projStoresDtos.size();i++){
			if(projStoresDtos.get(i).getName().equals(name)){
				id=projStoresDtos.get(i).getId();
			}else if(projStoresDtos.get(i).getName().equals("无门店")){
				id="-1";
			}
		}
		return id;
	}
		
	
	private void addComRecord(){
		if(StringUtil.isBlank(showProject.getText().toString())){
			Util.sendToast(AddCommicationRecordActivity.this, "项目不能为空!");
			return;
		}
		if(StringUtil.isBlank(showShop.getText().toString())){
			Util.sendToast(AddCommicationRecordActivity.this, "终端不能为空!");
			return;
		}
		if(StringUtil.isBlank(title.getText().toString())){
			title.setError("标题不能为空");
			return;
		}
		if(StringUtil.isBlank(title.getText().toString().trim())){
			title.setError("标题不能为空");
			return;
		}
		if(StringUtil.isBlank(showTel.getText().toString())){
			Util.sendToast(AddCommicationRecordActivity.this, "沟通方式不能为空!");
			return;
		}
		if(StringUtil.isBlank(showTel.getText().toString().trim())){
			Util.sendToast(AddCommicationRecordActivity.this, "沟通方式不能为空!");
			return;
		}
		if(StringUtil.isBlank(name.getText().toString())){
			name.setError("姓名不能为空!");
			return;
		}
		if(StringUtil.isBlank(name.getText().toString().trim())){
			name.setError("姓名不能为空!");
			return;
		}
		if(StringUtil.isBlank(occupation.getText().toString())){
			occupation.setError("职位不能为空!");
			return;
		}
		if(StringUtil.isBlank(occupation.getText().toString().trim())){
			occupation.setError("职位不能为空!");
			return;
		}
		if(StringUtil.isBlank(tel.getText().toString())){
			tel.setError("联系方式不能为空!");
			return;
		}
		if(StringUtil.isBlank(tel.getText().toString().trim())){
			tel.setError("联系方式不能为空!");
			return;
		}
		if(StringUtil.isBlank(content.getText().toString().trim())){
			content.setError("沟通内容部能为空!");
			return;
		}
		addCommunicationToServer.setUserId(getCurrentUser().getId());
		addCommunicationToServer.setProjId(findSelectedProjectId(showProject.getText().toString()));
		addCommunicationToServer.setProjStoreId(findSelectedShopId(showShop.getText().toString()));
		addCommunicationToServer.setTitle(title.getText().toString().trim());
		addCommunicationToServer.setType(showTel.getText().toString());
		addCommunicationToServer.setContactName(name.getText().toString().trim());
		addCommunicationToServer.setContactPosition(occupation.getText().toString().trim());
		addCommunicationToServer.setContactPhoneOrOther(tel.getText().toString().trim());
		addCommunicationToServer.setContent(content.getText().toString().trim());
		CommunicationSend.addCommunication(addCommunicationToServer);
	
	
		addCommunicationToDb.setUserId(getCurrentUser().getId()+"");
		addCommunicationToDb.setProjId(showProject.getText().toString());
		addCommunicationToDb.setProjStoreId(showShop.getText().toString());
		addCommunicationToDb.setTitle(title.getText().toString());
		addCommunicationToDb.setType(showTel.getText().toString());
		addCommunicationToDb.setContactName(name.getText().toString());
		addCommunicationToDb.setContactPosition(occupation.getText().toString());
		addCommunicationToDb.setContactPhoneOrOther(tel.getText().toString());
		addCommunicationToDb.setContent(content.getText().toString());
		communicationDbOperation.save(addCommunicationToDb);
		Intent intent=new Intent(AddCommicationRecordActivity.this,CommunicationActivity.class);
		setResult(RESULT_OK, intent);
		finish();
	}
	
	
	
	
	public void isAddServerSuccess(MessageInfo messageInfo){
//		if (messageInfo.getCode().equals("user004")){
//			Util.sendToast(mContext, "必须选择项目或终端");
//		}else if (messageInfo.getCode().equals("common001")){
//			Util.sendToast(mContext, "添加成功");
//			finish();
//		}else if (messageInfo.getCode().equals("user005")){
//			Util.sendToast(mContext, "必须填写标题");
//		}else if (messageInfo.getCode().equals("user006")){
//			Util.sendToast(mContext, "项目或终端不存在");
//		}
		Util.sendToast(mContext, messageInfo.getContent());
	}
	
	public TextWatcher textWatcher=new TextWatcher() {
		
		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void afterTextChanged(Editable s) {
			// TODO Auto-generated method stub
			if(!RegexPattern.isNumber(s.toString())&&s.length()>0){
//				for(EditText et:EditList.get(index)){
//					if(et.getText().toString().equals(s.toString())){
//						et.setError("只能输入数字！");
//					}
//				}
			}
		}
	};
	
	
	
	
	public void showProjectAndStoreFromServer(MessageInfo messageInfo){
//		if (messageInfo.getCode().equals("common003")){
			Util.sendToast(AddCommicationRecordActivity.this, messageInfo.getContent());
//		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
//		if(handler!=null){
//			handler=null;
//		}
	}
		
	
	
}
